/*
 * Copyright (C) 2011, EADS France
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 */
package xowl.interpreter.backends.rete;

import java.util.Collection;
import java.util.Iterator;

/**
 *
 * @author Laurent WOUTERS
 */
public class FilterNode implements FactActivable {
    private FactHolder parent;
    private Filter filter;
    private AlphaMemory child;
    
    public AlphaMemory getChild() { return child; }
    
    public FilterNode(FactHolder alpha, Filter filter) {
        this.parent = alpha;
        this.filter = filter;
        this.child = new AlphaMemory();
        this.parent.addChild(this);
        int size = this.parent.getFacts().size();
        if (size != 0) {
            if (size == 1)
                activateFact(this.parent.getFacts().iterator().next());
            else
                activateFacts(new FastBuffer<TripleFact>(this.parent.getFacts()));
        }
    }
    
    @Override public void activateFact(TripleFact fact) {
        if (filter.pass(fact))
            child.activateFact(fact);
    }
    @Override public void deactivateFact(TripleFact fact) {
        if (filter.pass(fact))
            child.deactivateFact(fact);
    }
    @Override public void activateFacts(Collection<TripleFact> facts) {
        applyFilter(facts);
        if (!facts.isEmpty())
            child.activateFacts(facts);
    }
    @Override public void deactivateFacts(Collection<TripleFact> facts) {
        applyFilter(facts);
        if (!facts.isEmpty())
            child.deactivateFacts(facts);
    }
    
    private void applyFilter(Collection<TripleFact> facts) {
        Iterator<TripleFact> iter = facts.iterator();
        while (iter.hasNext()) {
            TripleFact current = iter.next();
            if (!filter.pass(current))
                iter.remove();
        }
    }
}
